package com.web.surf.sample.eshop.faces.navigation;

import javax.faces.event.ActionEvent;
import com.web.surf.sample.eshop.faces.backing.beans.DataPager;

/**
 * Navigation by next previous first and last buttons
 * 
 * @author SavenkoNV
 */
public class PagerStepNavigator {

	private DataPager pager;

	public void pageFirst(ActionEvent event) {
		navigate(0, 1);
	}

	public void pageNext(ActionEvent event) {
		int firstRow = pager.getFirstRow() + pager.getRowsPerPage();
		int currentPage = pager.getCurrentPage() + 1;
		navigate(firstRow, currentPage);
	}

	public void pagePrevious(ActionEvent event) {
		int firstRow = pager.getFirstRow() - pager.getRowsPerPage();
		int currentPage = pager.getCurrentPage() - 1;
		navigate(firstRow, currentPage);
	}

	public void pageLast(ActionEvent event) {
		int firstRow = pager.getTotalRows()
				- ((pager.getTotalRows() % pager.getRowsPerPage() != 0) ? pager
						.getTotalRows()
						% pager.getRowsPerPage() : pager.getRowsPerPage());
		int currentPage = pager.getTotalPages();
		navigate(firstRow, currentPage);
	}

	private void navigate(int currentFirstRow, int currentPage) {
		pager.setFirstRow(currentFirstRow);
		pager.setCurrentPage(currentPage);
		pager.executeNavigation(currentFirstRow);
	}

	// Spring setter
	public void setPager(DataPager pager) {
		this.pager = pager;
	}
}